package course.d1230;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
   案例：从客服端发送一个文件到服务端，服务端回写客户端，收到了并写入本地
 */
public class test {
    public static void main(String[] args) {
        try (Socket socket = new Socket("192.168.43.161",8888)) {
            OutputStream os = socket.getOutputStream();
            FileInputStream fis = new FileInputStream("hello\\客户端\\123.jpg");
            byte[] bs = new byte[1024];
            int read ;
            while ((read=fis.read(bs))!=-1){
                os.write(bs,0,read);
            }

            socket.shutdownOutput();

            InputStream is = socket.getInputStream();
            while ((read=is.read(bs))!=-1){
                System.out.println(new String(bs,0,read));
            }
                fis.close();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class Server{
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        while (true){
            Socket accept = server.accept();
            new Thread(()->{
                try  {
                    InputStream is = accept.getInputStream();
                    String name  = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                    FileOutputStream fos = new FileOutputStream("hello\\服务端\\"+name+".jpg");
                    int read;
                    byte[] bytes = new byte[1024];
                    while ((read=is.read(bytes))!=-1){
                        fos.write(bytes,0,read);
                    }

                    OutputStream os = accept.getOutputStream();
                    os.write("接收到了！！".getBytes());
                    accept.shutdownOutput();
                    fos.close();
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

        }

    }
}
